package com.mashibing.tomcat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @Auther: dy
 * @Date: 2022/1/1 - 01 - 01 - 21:15
 * @Description: web服务器 : 接收客户端请求, 做出对应的响应
 * @version: 1.0
 */
public class MyServer {
    /**javaWeb使用的是TCP协议:套接字连接*/

    /**服务器套接字*/
    private ServerSocket ss;

    /**接收客户端套接字*/
    private Socket socket;

    /**
     * 构造器
     * @param port 传入Server服务器端口
     */
    public MyServer(Integer port){
        try {
            //初始化服务器套接字
            this.ss = new ServerSocket(port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 执行服务器线程
     */
    public void startServer(){
        while (true){
            try {
                //阻塞: 来一个客户连接,创建一个连接线程
                socket = ss.accept();
                new Thread(new StartServer(socket)).start();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 执行服务器线程
     */
    public class StartServer implements Runnable{
        /**输入流*/
        private InputStream inputStream;

        /**输出流*/
        private OutputStream outputStream;

        public StartServer(Socket socket) {
            try {
                //初始化输入流
                inputStream = socket.getInputStream();
                //初始化输出流
                outputStream = socket.getOutputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void run() {
            try {
                //创建请求对象
                MyRequest myRequest = new MyRequest(inputStream);
                //创建响应对象
                MyResponse myResponse = new MyResponse(outputStream);
                //映射对应的Servlet applet服务器
                String servlet = new MyMapping().getMap().get(myRequest.toString());
                //利用反射获取Servlet applet程序字节码对象
                if (servlet != null) {
                    Class<MyServlet> servletClass = (Class<MyServlet>) Class.forName(servlet);
                    //利用字节码对象获取实例对象
                    MyServlet myServlet = servletClass.newInstance();
                    //执行server方法做出响应
                    myServlet.service(myRequest, myResponse);
                }
            } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
}
